import { useEffect, useMemo, useRef, useState } from 'react'
import { PlusIcon, PhotoIcon, HeartIcon, EllipsisVerticalIcon } from '@heroicons/react/24/outline'
import { HeartIcon as HeartIconSolid } from '@heroicons/react/24/solid'
import { albumsApi } from '@/services/albumsApi'
import type { Album, Photo } from '@/types/albums'
import { toast } from 'react-hot-toast'

const AlbumPage = () => {
  // Special id for "All Photos" view
  const ALL_ID = '__ALL__'

  // Albums
  const [albums, setAlbums] = useState<Album[]>([])
  const [albumMeta, setAlbumMeta] = useState<Record<string, { count: number; coverUrl?: string; updatedAt?: string }>>({})
  const [activeAlbumId, setActiveAlbumId] = useState<string | null>(null)

  // Photos of selected album
  const [photos, setPhotos] = useState<Photo[]>([])

  // Upload + refresh
  const fileInputRef = useRef<HTMLInputElement | null>(null)
  const [isUploading, setIsUploading] = useState(false)
  const [autoRefresh, setAutoRefresh] = useState(false)

  const activeAlbum = useMemo(() => albums.find(a => a.id === activeAlbumId) || null, [albums, activeAlbumId])

  // Helpers
  const formatDate = (dateStr?: string) => {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })
  }

  // Load albums
  const loadAlbums = async () => {
    try {
      const list = await albumsApi.listAlbums()
      setAlbums(list)
    } catch (e: any) {
      toast.error(e?.response?.data?.message || '加载相册失败')
    }
  }

  // Load photos for selected album
  const loadPhotos = async (albumId: string) => {
    try {
      const list = await albumsApi.listPhotos(albumId)
      setPhotos(list)
    } catch (e: any) {
      toast.error(e?.response?.data?.message || '加载照片失败')
    }
  }

  // Load all photos across all albums (merged and sorted desc)
  const loadAllPhotos = async () => {
    try {
      const list = await albumsApi.listAlbums()
      if (!list.length) {
        setPhotos([])
        return
      }
      const tasks = list.map(a => albumsApi.listPhotos(a.id))
      const results = await Promise.allSettled(tasks)
      const merged: Photo[] = []
      for (const r of results) {
        if (r.status === 'fulfilled') merged.push(...r.value)
      }
      merged.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
      setPhotos(merged)
    } catch (e: any) {
      toast.error(e?.response?.data?.message || '加载全部照片失败')
    }
  }

  // Compute album meta (cover/qty/updatedAt) lazily and cache
  const computeAlbumMeta = async (list: Album[]) => {
    if (!list.length) return
    const tasks = list
      .filter(a => !albumMeta[a.id])
      .map(async (a) => {
        try {
          const plist = await albumsApi.listPhotos(a.id)
          const count = plist.length
          const coverUrl = plist[0]?.url
          const updatedAt = plist.reduce((latest, p) => {
            const t = new Date(p.createdAt).getTime()
            return t > latest ? t : latest
          }, 0)
          return [a.id, { count, coverUrl, updatedAt: updatedAt ? new Date(updatedAt).toISOString() : a.createdAt }] as const
        } catch {
          return [a.id, { count: 0, updatedAt: a.createdAt }] as const
        }
      })
    if (!tasks.length) return
    const results = await Promise.all(tasks)
    setAlbumMeta(prev => {
      const next = { ...prev }
      let allCount = 0
      let allLatest = 0
      let allCover: string | undefined
      for (const [id, meta] of results) {
        next[id] = meta
        const count = meta.count || 0
        allCount += count
        const latest = meta.updatedAt ? new Date(meta.updatedAt).getTime() : 0
        if (latest > allLatest) {
          allLatest = latest
          if (meta.coverUrl) allCover = meta.coverUrl
        }
      }
      next[ALL_ID] = {
        count: allCount,
        coverUrl: allCover,
        updatedAt: allLatest ? new Date(allLatest).toISOString() : undefined
      }
      return next
    })
  }

  // Init
  useEffect(() => {
    loadAlbums()
  }, [])

  // When albums change, try to compute meta
  useEffect(() => {
    if (albums.length) computeAlbumMeta(albums)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [albums])

  // When select album, load photos (album or all)
  useEffect(() => {
    if (!activeAlbumId) return
    if (activeAlbumId === ALL_ID) {
      loadAllPhotos()
    } else {
      loadPhotos(activeAlbumId)
    }
  }, [activeAlbumId])

  // Auto refresh: if album selected -> refresh photos (ALL uses merged); else -> refresh albums
  useEffect(() => {
    if (!autoRefresh) return
    const t = setInterval(async () => {
      try {
        if (activeAlbumId) {
          if (activeAlbumId === ALL_ID) {
            await loadAllPhotos()
          } else {
            await loadPhotos(activeAlbumId)
          }
        } else {
          await loadAlbums()
        }
      } catch {}
    }, 10000)
    return () => clearInterval(t)
  }, [autoRefresh, activeAlbumId])

  // Actions
  const onCreateAlbum = async () => {
    const title = prompt('输入新相册名称')
    if (!title) return
    try {
      await albumsApi.createAlbum(title.trim())
      toast.success('相册已创建')
      await loadAlbums()
    } catch (e: any) {
      toast.error(e?.response?.data?.message || '创建相册失败')
    }
  }

  const onRefresh = async () => {
    try {
      if (activeAlbumId) {
        if (activeAlbumId === ALL_ID) {
          await loadAllPhotos()
        } else {
          await loadPhotos(activeAlbumId)
        }
      }
      await loadAlbums()
      toast.success('已刷新')
    } catch {}
  }

  const onClearSelection = async () => {
    setActiveAlbumId(null)
    setPhotos([])
    await loadAlbums()
  }

  const onUploadClick = () => {
    if (!activeAlbumId) {
      toast.error('请先选择相册')
      return
    }
    if (activeAlbumId === ALL_ID) {
      toast.error('请先选择具体相册后再上传')
      return
    }
    fileInputRef.current?.click()
  }

  const onFileSelected = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file || !activeAlbumId) return
    try {
      setIsUploading(true)
      await albumsApi.uploadPhoto(activeAlbumId, file)
      await loadPhotos(activeAlbumId)
      // 更新封面/数量缓存
      setAlbumMeta(prev => {
        const meta = prev[activeAlbumId] || { count: 0 }
        return {
          ...prev,
          [activeAlbumId]: {
            count: (meta.count ?? 0) + 1,
            coverUrl: meta.coverUrl || URL.createObjectURL(file),
            updatedAt: new Date().toISOString()
          }
        }
      })
      toast.success('上传成功')
    } catch (e: any) {
      toast.error(e?.response?.data?.message || '上传失败')
    } finally {
      setIsUploading(false)
      if (fileInputRef.current) fileInputRef.current.value = ''
    }
  }

  const toggleLike = async (photoId: string) => {
    try {
      const updated = await albumsApi.toggleLike(photoId)
      setPhotos(prev => prev.map(p => p.id === photoId ? updated : p))
    } catch (e: any) {
      toast.error(e?.response?.data?.message || '操作失败')
    }
  }

  const [selectedPhoto, setSelectedPhoto] = useState<Photo | null>(null)

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-3">
          {!activeAlbumId ? (
            <>全部相册 <span className="text-gray-500 text-base">({albums.length})</span></>
          ) : (
            <>
              <button onClick={onClearSelection} className="btn-secondary">返回</button>
              <span>{activeAlbumId === ALL_ID ? '全部照片' : (activeAlbum?.title || '')}</span>
            </>
          )}
        </h1>
        <div className="flex items-center gap-3">
          {/* 移动端：仅保留上传 + 更多菜单 */}
          <div className="flex items-center gap-2 sm:hidden">
            <button
              onClick={onUploadClick}
              className="btn-primary flex items-center gap-2"
              disabled={!activeAlbumId || isUploading}
            >
              <PlusIcon className="h-5 w-5" />
              {isUploading ? '上传中...' : '上传照片'}
            </button>
            <div className="relative">
              <button className="btn btn-sm btn-outline" onClick={(e) => {
                const menu = (e.currentTarget.nextElementSibling as HTMLDivElement | null)
                if (menu) menu.classList.toggle('hidden')
              }}>
                <EllipsisVerticalIcon className="h-5 w-5" />
              </button>
              <div className="absolute right-0 mt-2 w-40 bg-white border border-gray-200 rounded-lg shadow-lg hidden z-10">
                <button className="w-full text-left px-3 py-2 hover:bg-gray-50 text-sm" onClick={onCreateAlbum}>新建相册</button>
                <button className="w-full text-left px-3 py-2 hover:bg-gray-50 text-sm" onClick={onRefresh}>刷新</button>
                <button className="w-full text-left px-3 py-2 hover:bg-gray-50 text-sm" onClick={onClearSelection}>清除选择</button>
                <label className="flex items-center gap-2 px-3 py-2 text-sm text-gray-700">
                  <input type="checkbox" checked={autoRefresh} onChange={(e) => setAutoRefresh(e.target.checked)} />
                  自动刷新
                </label>
              </div>
            </div>
          </div>

          {/* 桌面端：保持完整工具栏 */}
          <div className="hidden sm:flex items-center gap-3">
            <button onClick={onCreateAlbum} className="btn-secondary">新建相册</button>
            <button onClick={onRefresh} className="btn-secondary">刷新</button>
            <label className="inline-flex items-center gap-2 text-sm text-gray-600">
              <input type="checkbox" checked={autoRefresh} onChange={(e) => setAutoRefresh(e.target.checked)} />
              自动刷新
            </label>
            <button onClick={onClearSelection} className="btn-secondary">清除选择</button>
            <button onClick={onUploadClick} className="btn-primary flex items-center gap-2" disabled={!activeAlbumId || isUploading}>
              <PlusIcon className="h-5 w-5" />
              {isUploading ? '上传中...' : '上传照片'}
            </button>
          </div>

          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            onChange={onFileSelected}
            className="hidden"
          />
        </div>
      </div>

      {/* Albums Grid: only when no album selected */}
      {!activeAlbumId && (
        <div>

          <div className="grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-2 sm:gap-3 lg:gap-4">
            {/* 全部照片入口卡片（封面/数量/最近更新时间） */}
            <div
              className="card overflow-hidden hover:shadow-lg transition-shadow cursor-pointer"
              onClick={() => setActiveAlbumId(ALL_ID)}
              title="全部照片"
            >
              <div className="aspect-square bg-gray-100 flex items-center justify-center overflow-hidden">
                {albumMeta[ALL_ID]?.coverUrl ? (
                  <img
                    src={albumMeta[ALL_ID]!.coverUrl!}
                    alt="全部照片"
                    loading="lazy"
                    className="w-full h-full object-cover"
                  />
                ) : (
                  <PhotoIcon className="h-6 w-6 sm:h-8 sm:w-8 text-gray-400" />
                )}
              </div>
              <div className="p-2 sm:p-3">
                <h3 className="font-semibold text-gray-900 mb-1 line-clamp-1 text-xs sm:text-sm">全部照片</h3>
                <div className="text-xs text-gray-500">
                  <span>{albumMeta[ALL_ID]?.count ?? 0} 张</span>
                </div>
              </div>
            </div>

            {albums.map((a) => {
              const meta = albumMeta[a.id]
              return (
                <div
                  key={a.id}
                  className="card overflow-hidden hover:shadow-lg transition-shadow cursor-pointer"
                  onClick={() => setActiveAlbumId(a.id)}
                  title={a.title}
                >
                  <div className="aspect-square bg-gray-100 flex items-center justify-center overflow-hidden">
                    {meta?.coverUrl ? (
                      <img
                        src={meta.coverUrl}
                        alt={a.title}
                        loading="lazy"
                        className="w-full h-full object-cover"
                      />
                    ) : (
                      <PhotoIcon className="h-6 w-6 sm:h-8 sm:w-8 text-gray-400" />
                    )}
                  </div>
                  <div className="p-2 sm:p-3">
                    <h3 className="font-semibold text-gray-900 mb-1 line-clamp-1 text-xs sm:text-sm">{a.title}</h3>
                    <div className="text-xs text-gray-500">
                      <span>{meta?.count ?? 0} 张</span>
                    </div>
                  </div>
                </div>
              )
            })}
            {albums.length === 0 && (
              <div className="col-span-full text-center py-12">
                <PhotoIcon className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <h3 className="text-lg font-medium text-gray-900 mb-2">还没有相册</h3>
                <p className="text-gray-600 mb-6">创建一个相册，开始收集你们的回忆</p>
                <button className="btn-primary" onClick={onCreateAlbum}>新建相册</button>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Photos Section: when viewing 'All Photos' or a specific album */}
      {activeAlbumId !== null && (
        <div className="space-y-4">
          {/* Controls */}


          {/* Photos Grid (responsive columns) */}
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-2 sm:gap-3 lg:gap-4">
            {photos.map((photo) => (
              <div
                key={photo.id}
                className="card overflow-hidden cursor-pointer hover:shadow-lg transition-shadow"
                onClick={() => setSelectedPhoto(photo)}
              >
                <div className="relative">
                  <img
                    src={photo.url}
                    alt={photo.title}
                    loading="lazy"
                    className="w-full aspect-square object-cover"
                  />
                  <button
                    onClick={(e) => {
                      e.stopPropagation()
                      toggleLike(photo.id)
                    }}
                    className="absolute top-1 right-1 p-1 bg-white/80 rounded-full hover:bg-white transition-colors"
                  >
                    {photo.liked ? (
                      <HeartIconSolid className="h-3 w-3 sm:h-4 sm:w-4 text-red-500" />
                    ) : (
                      <HeartIcon className="h-3 w-3 sm:h-4 sm:w-4 text-gray-600" />
                    )}
                  </button>
                </div>
                <div className="p-2 sm:p-3">
                  <h3 className="font-semibold text-gray-900 mb-1 line-clamp-1 text-xs sm:text-sm">{photo.title}</h3>
                  {photo.description && (
                    <p className="text-xs text-gray-600 mb-1 line-clamp-1 hidden sm:block">{photo.description}</p>
                  )}
                  <div className="text-xs text-gray-500">
                    <span className="hidden sm:inline">{formatDate(photo.createdAt)}</span>
                    <span className="sm:hidden">{new Date(photo.createdAt).toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })}</span>
                  </div>
                  {photo.tags.length > 0 && (
                    <div className="flex flex-wrap gap-1 mt-1 hidden sm:flex">
                      {photo.tags.slice(0, 2).map((tag) => (
                        <span
                          key={tag}
                          className="px-1 py-0.5 bg-gray-100 text-gray-600 text-xs rounded-full"
                        >
                          #{tag}
                        </span>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>

          {/* Empty state */}
          {photos.length === 0 && (
            <div className="text-center py-12">
              <PhotoIcon className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">还没有上传照片</h3>
              <p className="text-gray-600 mb-6">开始上传你们的美好回忆吧</p>
              <button className="btn-primary" onClick={onUploadClick} disabled={isUploading}>
                {isUploading ? '上传中...' : '上传第一张照片'}
              </button>
            </div>
          )}
        </div>
      )}

      {/* Photo modal */}
      {selectedPhoto && (
        <div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg max-w-4xl max-h-full overflow-auto">
            <div className="p-6">
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-xl font-bold text-gray-900">
                  {selectedPhoto.title}
                </h2>
                <button
                  onClick={() => setSelectedPhoto(null)}
                  className="text-gray-400 hover:text-gray-600"
                >
                  ✕
                </button>
              </div>
              <img
                src={selectedPhoto.url}
                alt={selectedPhoto.title}
                className="w-full max-h-96 object-contain mb-4"
              />
              <div className="space-y-3">
                {selectedPhoto.description && (
                  <p className="text-gray-700">{selectedPhoto.description}</p>
                )}
                <div className="flex items-center justify-between text-sm text-gray-500">
                  <span>上传于 {formatDate(selectedPhoto.createdAt)}</span>
                  <span>by {selectedPhoto.userId.slice(-4)}</span>
                </div>
                {selectedPhoto.tags.length > 0 && (
                  <div className="flex flex-wrap gap-2">
                    {selectedPhoto.tags.map((tag) => (
                      <span
                        key={tag}
                        className="px-3 py-1 bg-gray-100 text-gray-600 text-sm rounded-full"
                      >
                        #{tag}
                      </span>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default AlbumPage